import { createSlice } from "@reduxjs/toolkit";
import { User } from "screens/project-list/serarch-panel";
import * as auth from "auth-provider"
import { AuthForm, bootstrapUser } from "context/auth-context";
import { AppDispach, RootState } from "store";
interface State {
  user: User | null
}
const initialState: State = {
  user: null
}
export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setUser(state, action) { state.user = action.payload }
  }
})
const { setUser } = authSlice.actions

export const selectUser = (state: RootState) => state.auth.user
export const login = (form: AuthForm) => (dispatch: AppDispach) => auth.login(form).then(user => dispatch(setUser(user)))
export const register = (form: AuthForm) => (dispatch: AppDispach) => auth.register(form).then(user => dispatch(setUser(user)))
export const logOut = () => (dispatch: AppDispach) => auth.logout().then(user => dispatch(setUser(null)))
export const bootstrap = () => (dispatch: AppDispach) => bootstrapUser().then(user => dispatch(setUser(user)))